package my.download;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import my.download.pojo.Download2;
import my.download.util.ExcelUtils;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@Slf4j
public class Application1 {

    public static void main(String[] args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            ClassicHttpRequest imageReq = ClassicRequestBuilder.get("https://risk-approval.mldigits.com:20004/prod-api/captchaImage")
                    .setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                    .setHeader("Accept-Encoding", "gzip, deflate, br")
                    .setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .setHeader("Cache-Control", "max-age=0").build();
            String respStr = httpclient.execute(imageReq, entity -> EntityUtils.toString(entity.getEntity()));
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(respStr);
            byte[] bytes = Base64.getDecoder().decode(jsonNode.get("img").asText());
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
            JFrame jFrame = new JFrame();
            jFrame.setLayout(new FlowLayout());
            jFrame.setSize(500, 500);

            JLabel nameLabel = new JLabel("用户名：");
            JTextField nameField = new JTextField(40);
            jFrame.add(nameLabel);
            jFrame.add(nameField);

            JLabel pwdLabel = new JLabel("密码：");
            JTextField pwdField = new JTextField(40);
            jFrame.add(pwdLabel);
            jFrame.add(pwdField);

            JLabel jLabel = new JLabel(new ImageIcon(image));
            JTextField field = new JTextField(10);
            JButton button = new JButton("开始下载");

            jFrame.add(jLabel);
            jFrame.add(field);
            jFrame.add(button);

            jFrame.setVisible(true);
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            button.addActionListener(e -> {
                String text = field.getText();
                jFrame.setVisible(false);
                try {
                    download(jsonNode.get("uuid").asText(), nameField.getText(), pwdField.getText(), text);
                } catch (InterruptedException ex) {
                    // ignore
                }
            });
        }
    }

    private static void download(String uuid, String name, String pwd, String code) throws InterruptedException {
        log.info("下载开始：需要大概5-10分钟，请耐心等候！");
        String fileName = "导出-" + System.currentTimeMillis() + ".xlsx";
        String fullName = System.getProperty("user.dir") + "/" + fileName;

        ObjectMapper objectMapper = new ObjectMapper();
        Path path = Paths.get(fullName);
        try (CloseableHttpClient httpclient = HttpClients.createDefault();
             OutputStream out = Files.newOutputStream(path)) {
            ClassicHttpRequest loginReq = ClassicRequestBuilder.post("https://risk-approval.mldigits.com:20004/prod-api/login")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                    .setEntity("{\"username\":\""+name+"\",\"password\":\""+pwd+"\",\"code\":\""+code+"\",\"uuid\":\""+uuid+"\"}", ContentType.APPLICATION_JSON)
                    .build();
            String respStr = httpclient.execute(loginReq, entity -> EntityUtils.toString(entity.getEntity()));
            log.info(respStr);
            String token = objectMapper.readTree(respStr).get("token").asText();
            List<Download2> res = new ArrayList<>();
            int count = 0;
            for (int i = 1; i <= 10000; i++) {
                ClassicHttpRequest dataRequest = ClassicRequestBuilder.post("https://smart-capital.mldigits.com:18002/gateway/collection/newBillInfo/getBillInfoList")
                        .setEntity("{" +
                                "\"innerType\": 2," +
                                "\"current\": "+ i +"," +
                                "\"overdueAgeType\": 3," +
                                "\"size\": 1000," +
                                "\"caseType\": \"2\"," +
                                "\"allocationStatus\": 1," +
                                "\"sortField\": \"overdue_days asc\"" +
                                "}", ContentType.APPLICATION_JSON)
                        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                        .addHeader("Authorization", token).build();
                String respBody = httpclient.execute(dataRequest, response -> EntityUtils.toString(response.getEntity()));
                JsonNode jsonNode = objectMapper.readTree(respBody);
                JsonNode dataArray = jsonNode.get("data");
                if (dataArray == null || dataArray.size() <= 0) {
                    break;
                }
                int total = jsonNode.get("totalCount").asInt();
                for (JsonNode data : dataArray) {
                    String billNo = data.get("billNo").asText();
                    ClassicHttpRequest dataReq = ClassicRequestBuilder.get("https://smart-capital.mldigits.com:18002/gateway/collection/newBillInfo/getBillDetailInfo?billNo=" + billNo)
                            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                            .addHeader("Authorization", token).build();
                    respBody = httpclient.execute(dataReq, response -> EntityUtils.toString(response.getEntity()));
                    JsonNode detailData = objectMapper.readTree(respBody).get("data");

                    String productName = detailData.get("productName").asText();
                    String loanDate = detailData.get("loanDate").asText();
                    String loanAmt = detailData.get("loanAmt").asText();
                    String periods = detailData.get("periods").asText();
                    String repaymentPeriods = detailData.get("repaymentPeriods").asText();
                    String overdueDays = detailData.get("overdueDays").asText();
                    String upToTodayLeftAmt = detailData.get("upToTodayLeftAmt").asText();
                    JsonNode customer = detailData.get("billCustomerVO");
                    String borrowerName = customer.get("borrowerName").asText();
                    String borrowerPhone = customer.get("borrowerPhone").asText();
                    String companyName = customer.get("companyName").asText();
                    String companyAddress = customer.get("companyAddress").asText();
                    String borrowerIdNo = customer.get("borrowerIdNo").asText();
                    String domicile = customer.get("domicile").asText();

                    ClassicHttpRequest relationReq = ClassicRequestBuilder.post("https://smart-capital.mldigits.com:18002/gateway/collection/case/phone/list")
                            .setEntity("{\"current\":1,\"size\":10,\"billNo\":\"" + billNo + "\"}", ContentType.APPLICATION_JSON)
                            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                            .addHeader("Authorization", token).build();
                    respBody = httpclient.execute(relationReq, response -> EntityUtils.toString(response.getEntity()));
                    JsonNode relationDataArr = objectMapper.readTree(respBody).get("data");
                    StringBuilder relationSb = new StringBuilder();
                    if (relationDataArr != null && !relationDataArr.isEmpty()) {
                        for (JsonNode relationData : relationDataArr) {
                            relationSb.append(relationData.get("name").asText()).append(" ");
                            relationSb.append(relationData.get("phone").asText()).append(" ");
                            relationSb.append(relationData.get("relation").asText()).append(" ");
                        }
                    }
                    String relation = relationSb.toString();

                    res.add(new Download2(
                            productName,
                            loanDate,
                            loanAmt,
                            periods + "/" + repaymentPeriods,
                            overdueDays,
                            upToTodayLeftAmt,
                            borrowerName,
                            borrowerPhone,
                            companyName,
                            companyAddress,
                            borrowerIdNo,
                            domicile,
                            relation
                    ));
                    log.info("下载进度：{}%", count++ * 100 / total);
                }
            }
            String[][] headers = {
                    {"产品类型", "productName"},
                    {"放款日期", "loanDate"},
                    {"借款金额", "loanAmt"},
                    {"期数/已还期数", "periods"},
                    {"逾期天数", "overdueDays"},
                    {"应还金额", "upToTodayLeftAmt"},
                    {"姓名", "borrowerName"},
                    {"手机号", "borrowerPhone"},
                    {"单位名称", "companyName"},
                    {"单位地址", "companyAddress"},
                    {"身份证号", "borrowerIdNo"},
                    {"户籍地址", "domicile"},
                    {"关系列表", "relation"},
            };
            ExcelUtils.exportExcel2007(fileName, headers, res, out);
            log.info("下载完成，请关闭窗口");
        } catch (Throwable e) {
            log.error("下载失败-", e);
            try {
                Files.deleteIfExists(path);
            } catch (IOException ignore) {}
            log.info("下载失败，请关闭窗口重试");
        }
    }

}
